package kz.kstu.scantest.business.client.key;





import com.sun.xml.internal.ws.api.streaming.XMLStreamWriterFactory;
import kz.kstu.scantest.business.entity.Key;
import kz.kstu.scantest.business.util.DateUtil;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;


/**
 * @author Filipp_Stankevich
 *         created 01.09.12 20:42
 */
public class KeyXmlCreator {

    public static final String ENCODING = "UTF-8";

    public String create(Key key) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {

            XMLStreamWriter writer = XMLStreamWriterFactory.create(outputStream, ENCODING);

            writer.writeStartDocument();

            writer.writeStartElement(KeyXmlTag.KEY);

            writer.writeStartElement(KeyXmlTag.DATA);

            writer.writeStartElement(KeyXmlTag.NUMBER);
            writer.writeCharacters(String.valueOf(key.getNumber()));
            writer.writeEndElement();

            writer.writeStartElement(KeyXmlTag.WRITE_OFF_COUNT);
            writer.writeCharacters(String.valueOf(key.getWriteOffCount()));
            writer.writeEndElement();

            writer.writeStartElement(KeyXmlTag.MAX_COUNT);
            writer.writeCharacters(String.valueOf(key.getMaxCount()));
            writer.writeEndElement();

            writer.writeStartElement(KeyXmlTag.EXPIRY_DATE);
            writer.writeCharacters(DateUtil.formatDate(key.getExpiryDate(), DateUtil.SIMPLE_DATE_PATTERN));
            writer.writeEndElement();

            writer.writeEndElement();

            writer.writeStartElement(KeyXmlTag.DIGEST);
            writer.writeCharacters(key.getDigest());
            writer.writeEndElement();

            writer.writeEndElement();

            writer.writeEndDocument();

            writer.close();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }

        try {
            return  outputStream.toString(ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Unknown encoding");
        }
    }

}
